package yzx.firstletter.appList;

import net.sourceforge.pinyin4j.PinyinHelper;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import yzx.firstletter.appList.fragment.LetterSelectFragment;
import yzx.firstletter.util.AppInstallUtil;

public class AppPinYinUtil {

    /** 排序app列表 */
    public static void sort(List<AppInstallUtil.AppInfo> list){
        Collections.sort(list, new FirstLetterSort());
    }
    /** 是否是数字 0-9 */
    public static boolean isNumber(char c){
        return (c+"").matches("\\d{1}");
    }
    /** 是否是字母 a-z A-Z */
    public static boolean isLetter(char c){
        return (c+"").matches("[a-zA-Z]");
    }
    /** 是否是汉字 */
    public static boolean isChinese(char c){
        return (c+"").matches("[\\u4e00-\\u9fa5]");
    }
    /** 获取第一个字母的大写 (比如: 你好->N, hello->H, {你好}-> {)*/
    public  static char getFirstLetterUpperCase(String str){
        if(str==null || str.trim().isEmpty())
            return ' ';
        char c = str.substring(0, 1).toUpperCase().charAt(0);
        String[] pinyin = PinyinHelper.toHanyuPinyinStringArray(c);
        if(pinyin==null) return c;
        return pinyin[0].substring(0, 1).toUpperCase().charAt(0);
    }
    /** 根据tag过滤app */
    public static List<AppInstallUtil.AppInfo> filterListByTag(List<AppInstallUtil.AppInfo> allList, String tag){
        if(!tag.equals(LetterSelectFragment.TAG_OTHER)&&!isLetter(tag.charAt(0)))
            throw new IllegalStateException("tag must be "+LetterSelectFragment.TAG_OTHER+" or a-z or A-Z");
        char tagChar = tag.charAt(0);
        ArrayList<AppInstallUtil.AppInfo> result = new ArrayList<>(allList.size()/4);
        boolean isOther = LetterSelectFragment.TAG_OTHER.equals(tag);
        for (AppInstallUtil.AppInfo info : allList) {
            char firstLetter = getFirstLetterUpperCase(info.name);
            if(isOther){
                if(isNumber(firstLetter)||!isLetter(firstLetter))
                    result.add(info);
            }else{
                if(firstLetter==tagChar)
                    result.add(info);
            }
        }
        return result;
    }



    /* 首字母拼音排序 */
    private static class FirstLetterSort implements Comparator<AppInstallUtil.AppInfo>{
        @Override
        public int compare(AppInstallUtil.AppInfo i1, AppInstallUtil.AppInfo i2) {
            char a = getFirstLetterUpperCase(i1.name);
            char b = getFirstLetterUpperCase(i2.name);
            if(a==b) return 0;
            if(a>b) return 1;
            return -1;
        }
    }

}
